<template>
  <div class="w-full min-h-screen bg-gray-50 text-gray-800 relative overflow-y-auto">
    <!-- 搜索栏 - 仅在推荐页面显示 -->
    <div class="search-header bg-white px-4 py-3 flex items-center space-x-3">
      <div class="flex-1 search-input-wrapper" @click="goToSearch">
        <i class="fas fa-search search-icon"></i>
        <div class="search-placeholder">搜索你喜欢的影片</div>
      </div>
    </div>

    <!-- 分类导航 -->
    <div class="category-nav bg-white px-4 pb-3 pt-2" :class="{ 'fixed-nav': isNavFixed }" ref="categoryNav">
      <!-- 顶部标签 -->
      <div class="flex items-center justify-between mb-3">
        <!-- 左侧主标签 -->
        <div class="flex space-x-6">
          <div
            v-for="tab in mainTabs"
            :key="tab.id"
            @click="switchMainTab(tab.id)"
            :class="
              activeMainTab === tab.id ? 'text-red-500 border-b-2 border-red-500 pb-1 font-medium' : 'text-gray-600'
            "
            class="cursor-pointer transition-colors"
          >
            {{ tab.name }}
          </div>
        </div>

        <!-- 右侧搜索按钮 - 只在固定导航时显示 -->
        <div
          v-if="isNavFixed"
          @click="goToSearch"
          class="search-btn flex items-center justify-center w-8 h-8 bg-gray-100 rounded-full cursor-pointer hover:bg-gray-200 transition-all duration-200 active:scale-95"
        >
          <i class="fas fa-search text-gray-600"></i>
        </div>
      </div>

      <!-- 分类标签 - 只在推荐标签下显示 -->
      <div
        v-if="activeMainTab === 'recommend' || activeMainTab === 'ranking'"
        class="horizontal-scroll"
        style="
          overflow-x: auto !important;
          overflow-y: hidden !important;
          -webkit-overflow-scrolling: touch !important;
          scrollbar-width: none !important;
          -ms-overflow-style: none !important;
        "
      >
        <!-- 加载中显示骨架屏 -->
        <div v-if="isLoading" class="flex space-x-3 py-1 px-1 category-skeleton">
          <div v-for="i in 5" :key="i" class="skeleton-item"></div>
        </div>

        <!-- 数据加载完成显示分类 -->
        <div
          v-else
          class="flex space-x-3 py-1 px-1"
          style="
            display: flex !important;
            flex-direction: row !important;
            flex-wrap: nowrap !important;
            width: max-content !important;
            min-width: 100% !important;
          "
        >
          <div
            v-for="(category, index) in allDramas"
            :key="category.id"
            @click="handleCategoryChange(category, index)"
            :class="activeCategory === index ? 'bg-red-500 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'"
            class="cursor-pointer px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition-all duration-200 flex-shrink-0 active:scale-95"
            style="flex-shrink: 0 !important"
          >
            {{ category.title }}
          </div>
        </div>
      </div>
    </div>

    <!-- 导航固定时的占位元素，避免内容跳动 -->
    <div v-if="isNavFixed" class="nav-placeholder"></div>

    <!-- 内容区域 -->
    <div class="px-4 pb-20 bg-gray-50">
      <!-- 加载状态 - 显示骨架屏 -->
      <div v-if="isLoading" class="pt-3">
        <div class="grid grid-cols-3 gap-3">
          <div v-for="i in 6" :key="i" class="content-skeleton">
            <div class="skeleton-img"></div>
            <div class="skeleton-text-short"></div>
            <div class="skeleton-text-long"></div>
          </div>
        </div>
      </div>

      <!-- 剧集列表 -->
      <div
        v-else-if="
          allDramas.length > 0 && allDramas[activeCategory].dramas && allDramas[activeCategory].dramas.length > 0
        "
        class="grid grid-cols-3 gap-3"
      >
        <div
          v-for="drama in allDramas[activeCategory].dramas"
          :key="drama.id"
          class="bg-white rounded-lg overflow-hidden shadow-sm cursor-pointer hover:shadow-md transition-shadow"
          @click="handleDramaClick(drama)"
        >
          <div class="relative">
            <img :src="drama.cover" class="w-full h-32 object-cover" :alt="drama.title" />
            <div
              v-if="drama.badge"
              class="absolute top-2 left-2 text-white text-xs px-1 rounded"
              :class="
                drama.isNew
                  ? 'bg-green-500'
                  : drama.isPopular
                    ? 'bg-red-500'
                    : drama.isExclusive
                      ? 'bg-green-600'
                      : 'bg-blue-500'
              "
            >
              {{ drama.isNew ? '新剧' : drama.isPopular ? '热热播' : drama.isExclusive ? '独家' : '' }}
            </div>
            <div class="absolute bottom-1 right-1 text-white text-xs bg-black bg-opacity-50 px-1 rounded">
              全{{ drama.totalEpisodes }}集
            </div>
          </div>
          <div class="p-2">
            <h3 class="text-sm font-medium mb-1 truncate">{{ drama.title }}</h3>
            <p class="text-xs text-gray-500 line-clamp-2">{{ drama.description }}</p>
          </div>
        </div>
      </div>

      <!-- 空状态占位符 -->
      <div v-else class="empty-state">
        <i class="far fa-sad-tear empty-icon"></i>
        <p class="empty-text">暂无剧集内容</p>
        <button
          v-if="activeCategory !== 0 || activeMainTab !== 'recommend'"
          @click="resetToDefault"
          class="mt-4 px-6 py-2 bg-red-500 text-white rounded-full text-sm hover:bg-red-600 transition-colors active:scale-95"
        >
          查看推荐剧集
        </button>
      </div>
    </div>

    <!-- Toast提示 -->
    <div v-if="showToast" class="toast-message">
      {{ toastMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
// 如果需要身份验证，可以在这里导入
import { reqHomeTabData } from '@/apis/video'

// 路由实例
const router = useRouter()

// 主要标签
const mainTabs = ref([
  { id: 'recommend', name: '推荐' },
  { id: 'newDrama', name: '新剧' },
  { id: 'ranking', name: '排行榜' },
  { id: 'classic', name: '经典好剧' }
])

// 标签和分类状态
const activeMainTab = ref('recommend')
const activeCategory = ref(0)

// 搜索状态
const searchQuery = ref('')
const showSearchPanel = ref(false)
const searchInput = ref(null)

// 搜索建议
const searchSuggestions = ref([
  '古装剧',
  '现代爱情',
  '悬疑推理',
  '科幻冒险',
  '校园青春',
  '家庭伦理',
  '历史传记',
  '甜宠恋爱'
])

// 剧集数据
const allDramas = ref([])
const isLoading = ref(false)

// 导航栏固定的响应式变量
const isNavFixed = ref(false)
const categoryNav = ref(null)
let navOffsetTop = 0

// 提示消息相关
const toastMessage = ref('')
const showToast = ref(false)

// 显示提示消息
const showToastMessage = (message) => {
  toastMessage.value = message
  showToast.value = true
  setTimeout(() => {
    showToast.value = false
  }, 2000)
}

// 跳转到搜索页面
const goToSearch = () => {
  router.push('/search')
}

// 重置到默认推荐
const resetToDefault = () => {
  activeMainTab.value = 'recommend'
  activeCategory.value = 0
  loadTheaterData('recommend')
}

// 加载剧场数据
const loadTheaterData = async (activeMainTab = 'recommend') => {
  try {
    isLoading.value = true
    console.log('🚀 开始加载剧场数据，标签:', activeMainTab)

    // 根据当前主标签加载数据
    const response = await reqHomeTabData(activeMainTab)

    // 检查数据结构并适配
    if (response.data) {
      // 尝试不同的数据结构
      let categories = null

      if (response.data.categories) {
        categories = response.data.categories
      } else if (response.data.data && response.data.data.categories) {
        categories = response.data.data.categories
      } else if (Array.isArray(response.data)) {
        categories = response.data
      } else if (response.data.dramas) {
        categories = [
          {
            id: 1,
            title: activeMainTab === 'newDrama' ? '新剧' : '经典好剧',
            dramas: response.data.dramas
          }
        ]
      } else {
        categories = [
          {
            id: 1,
            title: activeMainTab === 'newDrama' ? '新剧' : '经典好剧',
            dramas: []
          }
        ]
      }

      if (categories && categories.length > 0) {
        allDramas.value = categories
        activeCategory.value = 0
      } else {
        allDramas.value = []
        showToastMessage('没有找到剧集数据')
      }
    } else {
      allDramas.value = []
      showToastMessage('没有找到剧集数据')
    }
  } catch (error) {
    console.error('❌ 加载剧场数据失败:', error)
    allDramas.value = []
    showToastMessage('加载数据失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

// 处理剧集点击
const handleDramaClick = (drama) => {
  // 跳转到播放页面，传递剧集ID和videos数据
  console.log('点击剧集:', drama.title, 'ID:', drama.id)

  // 从第一集开始观看
  const episodeIndex = 0

  // 如果剧集有videos数据，直接传递
  if (drama.videos && drama.videos.length > 0) {
    router.push({
      name: 'Player',
      params: { dramaId: drama.id }
    })
  } else {
    // 否则只传递dramaId和episodeIndex，让播放页面自己获取数据
    router.push({
      name: 'Player',
      params: { dramaId: drama.id }
    })
  }
}

// 处理分类切换
const handleCategoryChange = (categotry, index) => {
  activeCategory.value = index
}

// 切换主标签时，重置分类为对应的默认值
const switchMainTab = (tabId) => {
  console.log('切换主标签:', tabId)

  // 先设置加载状态为true
  isLoading.value = true

  // 更新活动标签
  activeMainTab.value = tabId

  // 延迟一下再加载数据，确保UI先更新为骨架屏
  setTimeout(() => {
    loadTheaterData(activeMainTab.value)
  }, 100)
}

// 处理滚动事件
const handleScroll = () => {
  if (!categoryNav.value) return

  // 如果页面滚动超过导航栏的初始位置，将其固定
  if (window.scrollY > navOffsetTop) {
    isNavFixed.value = true
  } else {
    isNavFixed.value = false
  }
}

// 组件挂载时加载数据和设置滚动监听
onMounted(() => {
  loadTheaterData()

  // 延迟获取导航栏位置，确保DOM已完全加载
  setTimeout(() => {
    if (categoryNav.value) {
      // 获取导航栏相对于视口顶部的位置
      navOffsetTop = categoryNav.value.getBoundingClientRect().top + window.scrollY

      // 添加滚动事件监听
      window.addEventListener('scroll', handleScroll)
    }
  }, 300)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
/* 文本截断 - 限制为两行 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.2;
  /* 兼容性属性 */
  line-clamp: 2;
}

/* 分类标签的活跃状态优化 */
.cursor-pointer {
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

/* 防止滚动时的文字选择 */
.overflow-x-auto * {
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

/* 搜索栏样式统一 - 与搜索页面保持一致 */
.search-header {
  position: sticky;
  /* width: 100%; */
  top: 0;
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background-color: #fff;
  /* box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08); */
  z-index: 10;
  transition: all 0.3s ease;
}

.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  border-radius: 20px;
  background-color: #f5f5f7;
  height: 42px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
}

.search-icon {
  position: absolute;
  left: 15px;
  font-size: 14px;
  color: #8a8a8a;
}

.search-placeholder {
  margin-left: 40px;
  color: #a0a0a0;
  font-size: 15px;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 3rem 0;
  height: 30vh;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-top-color: #f97316;
  border-radius: 50%;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 1rem;
}

.loading-text {
  color: #666;
  font-size: 1rem;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 空数据状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 3rem 0;
  color: #9ca3af;
  height: 30vh;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
  color: #d1d5db;
}

.empty-text {
  font-size: 1rem;
}

/* 导航栏固定样式 */
.category-nav {
  z-index: 9;
  transition: all 0.3s ease;
  width: 100%;
}

.fixed-nav {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  padding-top: 10px; /* 增加上内边距 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  animation: slideDown 0.3s ease;
}

/* 导航占位元素，与导航高度一致，防止内容跳跃 */
.nav-placeholder {
  height: 90px; /* 调整高度以匹配导航栏高度+内边距 */
}

/* 搜索按钮动画效果 */
.search-btn {
  animation: fadeIn 0.3s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);
}

.search-btn i {
  font-size: 14px;
}

/* Toast提示样式 */
.toast-message {
  position: fixed;
  bottom: 5rem;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  z-index: 50;
}

@keyframes slideDown {
  from {
    transform: translateY(-100%);
  }
  to {
    transform: translateY(0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 隐藏滚动条但保留滚动功能 */
.horizontal-scroll::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
  width: 0;
  height: 0;
}

.horizontal-scroll {
  -ms-overflow-style: none; /* IE and Edge */
  scrollbar-width: none; /* Firefox */
  overflow-x: auto;
  overflow-y: hidden;
  -webkit-overflow-scrolling: touch;
}

/* 骨架屏样式 */
.category-skeleton {
  display: flex;
  width: 100%;
}

.skeleton-item {
  height: 36px;
  width: 80px;
  border-radius: 100px;
  background: linear-gradient(110deg, #f0f0f0 30%, #f8f8f8 50%, #f0f0f0 70%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  flex-shrink: 0;
}

.content-skeleton {
  background-color: white;
  border-radius: 0.5rem;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  padding-bottom: 8px;
}

.skeleton-img {
  height: 128px;
  width: 100%;
  background: linear-gradient(110deg, #f0f0f0 30%, #f8f8f8 50%, #f0f0f0 70%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-text-short {
  height: 16px;
  width: 80%;
  margin: 8px auto 4px;
  border-radius: 4px;
  background: linear-gradient(110deg, #f0f0f0 30%, #f8f8f8 50%, #f0f0f0 70%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-text-long {
  height: 12px;
  width: 90%;
  margin: 4px auto;
  border-radius: 4px;
  background: linear-gradient(110deg, #f0f0f0 30%, #f8f8f8 50%, #f0f0f0 70%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

@keyframes shimmer {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}
</style>
